package com.bodgittandscarper.brokerhmi.view;

import javax.swing.table.AbstractTableModel;

import com.bodgittandscarper.broker.types.DatabaseSchema;
import com.bodgittandscarper.broker.types.Record;

/**
 * TableModel for the RecordTable holding Records that matches search criteria.
 * 
 * @author Morten Rummelhoff
 *
 */
public class RecordTableModel extends AbstractTableModel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private DatabaseSchema databaseScheme;
	
	private Record[] tableData;
	
	public RecordTableModel(DatabaseSchema databaseScheme) {
		this.databaseScheme = databaseScheme;
	}
	
	/**
	 * Fetches from the tablemodel the corresponding record for the row.
	 * 
	 * @param row a row in the tablemodel.
	 * @return the Record for the given row. If row does not exist, null is returned.
	 */
	public Record getRecord(int row) {
		if (row < 0 && row > getRowCount()) {
			return null;
		}
		
		return tableData[row];
	}
	
	/**
	 * Updates the tablemodel with a new set of records. Note, that only the model is updated, not the tableview. 
	 * This must be done seperatly.
	 * 
	 * @param data the new Record data that matches a given search criteria.
	 */
	public void updateModel(Record[] data) {
		tableData = data;
	}
	
	@Override
	public String getColumnName(int col) {
		return this.databaseScheme.getDatabaseField(col).getFieldName().toUpperCase();
	}

	@Override
	public int getColumnCount() {
		return this.databaseScheme.getDatabaseFieldCount();
	}

	@Override
	public int getRowCount() {
		if (tableData != null) {
			return tableData.length;
		}
		else {
			return 0;
		}
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		switch (columnIndex) {
		case 3:
			return Integer.class;	
		case 4:
			return Number.class;	
		case 5:
			return Integer.class;
		}
		return String.class;
		
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		if (tableData == null || tableData.length < rowIndex)
			return null;

		Record recordRow = tableData[rowIndex];
		return recordRow.getRecordFields()[columnIndex].trim();
		
	}


}
